package com.rjkj.medicalwaste.ui.storage

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.rjkj.medicalwaste.R
import com.rjkj.medicalwaste.bean.*
import com.rjkj.medicalwaste.database.GarbageReviewWeightDialogInfo
import com.rjkj.medicalwaste.database.GarbageSetBoxed
import com.rjkj.medicalwaste.database.GarbageSetReviewAndBoxed
import com.rjkj.medicalwaste.database.GarbageSetUnReview
import com.rjkj.medicalwaste.databinding.DialogReviewWeightBinding
import com.rjkj.medicalwaste.databinding.DialogUnreviewWeightBinding
import com.rjkj.medicalwaste.utils.StrUtils
import com.rjkj.medicalwaste.utils.TimeUtils
import com.rjkj.medicalwaste.viewmodels.BluetoothControlViewModel
import com.rjkj.medicalwaste.viewmodels.ReviewWeightViewModel
import com.rjkj.medicalwaste.viewmodels.UnBoxedViewModel
import com.rjkj.medicalwaste.viewmodels.UserViewModel
import com.rjkj.medicalwaste.viewmodels.provider.MainViewModelProvider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.math.BigDecimal


class UnReviewWeightForBoxDialog : DialogFragment() {

    private val unBoxedViewModel: UnBoxedViewModel by viewModels {
        MainViewModelProvider.provideUnBoxedModel(requireContext())
    }
    private val userViewModel: UserViewModel by activityViewModels {
        MainViewModelProvider.provideUserModel(requireContext())
    }

    private val garbageViewModel: ReviewWeightViewModel by viewModels {
        MainViewModelProvider.providerReviewWeightModel(
            requireContext(), arguments?.getString(BoxListFragment.GARBAGE_TYPE)
                ?: ""
        )
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val binding = DialogUnreviewWeightBinding.inflate(inflater, container, false)
        binding.garbage = garbageViewModel
        binding.lifecycleOwner = viewLifecycleOwner
        onSubscribeUi(binding)
        return binding.root
    }

    private fun addToBox(value: GarbageReviewWeightDialogInfo) {
        val boxCode = arguments?.getString(BoxListFragment.BOX_CODE) ?: ""
        val boxType = arguments?.getString(BoxListFragment.BOX_TYPE) ?: ""
        Log.e("XLB", "boxCode: $boxCode")
        if (TextUtils.isEmpty(boxCode)||TextUtils.isEmpty(boxType)) {
            return
        }
        lifecycleScope.launch {
            val boxGarbageBean = unBoxedViewModel.repository.getBoxGarbageBean(
                userViewModel.hospitalId.value
                    ?: "", boxCode
            )
            Log.e("XLB", "boxGarbageBean: $boxGarbageBean")
            if (!boxGarbageBean.isNullOrEmpty()) {
                val garbageInBoxBean = GarbageInBoxBean(
                    garbageType = MedicalWasteType.getBoxTypeByTypeName(boxType),
                    garbageBoxQRCode = boxCode,
                    garbageList = boxGarbageBean,
                )
                val time = TimeUtils.getYMDHMSTime()
                unBoxedViewModel.repository.updateGarbageSetReviewAndBoxed(
                    GarbageSetReviewAndBoxed(
                        id = value.id,
                        garbageUserStatus = GarbageStatus.boxed,
                        garbageQRCode = value.garbageQRCode,
                        garbageBoxQRCode = boxCode,
                        garbageBoxDeviceSN = userViewModel.getSerial(),
                        garbageBoxTime = garbageInBoxBean.garbageBoxTime,
                        garbageBoxType = garbageInBoxBean.garbageType.typeName,
                        reviewWeightState = ReviewWeightState.CheckSuccess,
                        reviewDeviceSN = userViewModel.getSerial(),
                        reviewWeight = "0",
                        reviewType = "0",
                        reviewTime = time,
                    )
                )
                val finalBoxGarbageBean = unBoxedViewModel.repository.getBoxGarbageBean(
                    userViewModel.hospitalId.value
                        ?: "", boxCode
                )
                unBoxedViewModel.repository.updateChangeGarbageFromBox(
                    boxCode,
                    finalBoxGarbageBean.sumOf { BigDecimal(it.garbageWeight) }
                        .setScale(2, BigDecimal.ROUND_HALF_UP).toString(),
                    finalBoxGarbageBean.size,
                    time
                )
                val findList = unBoxedViewModel.repository.findGarbageByBoxCode(boxCode)
                Log.e("TAG", "addToBox: ${findList.toString()}")
                if (findList.isNotEmpty()) {
                    userViewModel.uploadGarbage(
                        garbageBeanList = findList,
                        successState = GarbageBean.storeState,
                        failState = GarbageBean.nullState
                    )
                }
            }
            delay(2000L)
            dismiss()
        }
    }

    fun onSubscribeUi(binding: DialogUnreviewWeightBinding) {
        binding.imClose.setOnClickListener {
            dismiss()
        }
        lifecycleScope.launch {
            val findGarbageReviewWeightDialogInfoByCode2 =
                garbageViewModel.garbageRepository.findGarbageReviewWeightDialogInfoByCode2(
                    arguments?.getString(
                        BoxListFragment.GARBAGE_TYPE
                    ) ?: ""
                )
            if (findGarbageReviewWeightDialogInfoByCode2 != null) {
                addToBox(findGarbageReviewWeightDialogInfoByCode2)
            }
        }


    }

    override fun onStart() {
        dialog!!.window!!.apply {
            attributes.gravity = Gravity.CENTER//位于底部
            decorView.background = ColorDrawable(Color.TRANSPARENT)//背景色
        }
        super.onStart()
    }


}
